from datetime import datetime, timedelta

def merge_and_calculate_total_time(time_ranges):
    # 将字符串转换为 datetime 对象
    time_ranges = [
        (datetime.strptime(start, '%Y-%m-%d %H:%M:%S.%f'), datetime.strptime(end, '%Y-%m-%d %H:%M:%S.%f'))
        for start, end in time_ranges
    ]

    # 排序时间段
    time_ranges.sort()

    # 合并连续时间段
    merged_ranges = []
    current_start, current_end = time_ranges[0]

    for start, end in time_ranges[1:]:
        if start <= current_end:  # 检查是否有重叠或相连
            current_end = max(current_end, end)
        else:
            merged_ranges.append((current_start, current_end))
            current_start, current_end = start, end

    # 添加最后一个时间段
    merged_ranges.append((current_start, current_end))

    # 计算总时间
    total_time = timedelta()
    for start, end in merged_ranges:
        total_time += (end - start)

    # 将 datetime 对象转换为字符串
    merged_ranges = [
        (start.strftime('%Y-%m-%d %H:%M:%S.%f')[:-3], end.strftime('%Y-%m-%d %H:%M:%S.%f')[:-3])
        for start, end in merged_ranges 
    ]

    return merged_ranges, total_time

# 示例调用
time_ranges = [
    ('2024-01-01 12:00:10.103', '2024-01-01 12:01:10.103'),
    ('2024-01-01 12:01:10.103', '2024-01-01 12:03:10.103'), 
    ('2024-01-01 12:02:10.303', '2024-01-01 12:04:10.103'),
    ('2024-01-01 12:05:10.103', '2024-01-01 12:07:10.111')
]

merged, total_time = merge_and_calculate_total_time(time_ranges)
print("Merged Ranges:", merged)
print("Total Time:", str(total_time)[:-3])
